const app = getApp();

//网络请求封装
import Request_post from "../../../../request/Request_post"
import Request_get from "../../../../request/Request_get"

//系统设置项目:(请求地址-在封装中已经引入，这里不需要;   api调用的Appid-partner_app_id;   渠道ID-as_appid)
import config from "../../../../config/config"

//引入时间函数
var dateArray = require("../../../../utils/CustomFunction/getDayFirstNowLast.js")
var time = require("../../../../utils/CustomFunction/getNowTime.js")

//引入日期时间：（格式化、反格式化、当前日期）函数
var formatDate = require("../../../../utils/CustomFunction/dateFormat.js")
var unformatDate = require("../../../../utils/CustomFunction/dateUnFormat.js")
var today = require("../../../../utils/CustomFunction//getToday.js")
var time = require("../../../../utils/CustomFunction/getNowTime.js")


Page({
  data: {
   
    // 资源图片：签到奖励
    Signin_Reward:config.imageUrl+"Sign_Reward.png",
    //签到奖励显示标志（默认不显示false）
    display_Signin_Reward:false, 
    
    close:config.imageUrl+"close.png",
    signined:config.imageUrl+"signined.png",


    //Title图片的网络地址链接（第一套：可换固定背景）
    Title_image:config.imageUrl+"title_member_signin.jpg",
    // theme: getApp().theme,
    todaySignin: 0,
    loading: true,
    jf:120 
  },

  //关闭新会员注册奖励
  Signin_Reward_show_off:function(){
    this.setData({
      display_Signin_Reward:false
    })
  },

  //未注册会员点击注册
  regNow:function(){
    wx.redirectTo({ 
      url:"/SubpkgPublicPage/pages/PublicPage/PrivacyPolicy/PolicyMain/PolicyMain"
    });
  },



  monthSignins: {},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function() {

    // 会员是否注册的标志regflg
    getApp().loginPromise.then(v => {	//app.js的Promise成功回调（全局变量赋值成功后才执行请求）
      this.setData({regflg: app.globalData.regflg})
      // console.log(App.globalData.regflg)
    })




    this.cur_date = new Date();
    this.today_ym = this.cur_date.getFullYear() * 100 + this.cur_date.getMonth() + 1;
    // 加载日历数据
    this.loadMonthCalendar();


    // (这里是我写的)-------------------
    this.setData({
      bllno: Math.round(new Date() / 1000),
      Today:unformatDate.DatString(today.getToday()),
      getTodayDtm: unformatDate.DatString(today.getToday()) + unformatDate.DatString(time.getNowTime()) 
    })

    var that = this
    getApp().loginPromise.then(v => {	//app.js的Promise成功回调（全局变量赋值成功后才执行请求）
    // Api请求：06-001 会员赚积分活动规则查询
      Request_get.get(
      config.domainName+'api_wxmkt_server/mbritgadd/findmbritgruladd',
      {
        additgactid:'03' //赚积分活动规则ID（01-新会员注册送积分、02-完善会员资料奖励积分、03-签到送积分）
      },
      function(res){
        that.setData({
          signinArray:res.return_data
        })
        const singinList = that.data.signinArray
        for(var i = 0 ; i < singinList.length ; i++){
          if(  //长期规则
            singinList[i].rulclsid == '01' && singinList[i].itgvlu > 0 &&  singinList[i].enldat <= that.data.getTodayDtm && singinList[i].disdat >= that.data.getTodayDtm){
            that.setData({
              longRulsigninItg:singinList[i].itgvlu
            })
          }else if(  //临时规则
            singinList[i].rulclsid == '02' && singinList[i].itgvlu > 0 && singinList[i].enldat <= that.data.getTodayDtm && singinList[i].disdat >= that.data.getTodayDtm){
            that.setData({
              shortRulsigninItg:singinList[i].itgvlu
            })
          }
        }
        //临时规则 和 长期规则 的最终赋值
        that.data.shortRulsigninItg > that.data.longRulsigninItg? that.setData({signinItg:that.data.shortRulsigninItg}): that.setData({signinItg:that.data.longRulsigninItg})
        // console.log(that.data.signinItg)
      })
    })
  },



  // 立即签到
  memberSignin:function(){
    this.cur_date = new Date();
    let today_ym = this.cur_date.getFullYear() * 100 + this.cur_date.getMonth() + 1;

    // (这里是我写的)------------------- 
    var that = this
    if(!that.data.signinItg){
      wx.showModal({
        content: '当前未设置签到积分奖励机制，不能进行签到操作',
        showCancel: true,		//是否显示取消按钮
        cancelText:"否",			//默认是“取消”
        cancelColor:'skyblue',		//取消文字的颜色
        confirmText:"是",		//默认是“确定”
        confirmColor: 'skyblue',	//确定文字的颜色
      })
      return;
    }

    // B15-会员签到
    Request_post.post(
    config.domainName+'api_wxmkt_server/mbrsgn/signwxmbr',
    {
      sgndat: that.data.Today
    },
    function(res){
      if(res != "undefined" && res.return_no == 1){
        that.loadMonthCalendar();
        // Api请求：06-002 会员积分增加
        Request_post.post(
        config.domainName+"api_wxmkt_server/mbritgadd/addmbritg",
        {
          oprcltid: config.cltid,
          oprid: "51",
          oprdat: that.data.getTodayDtm,
          srcbllno: app.globalData.mbrid + that.data.bllno,
          additgvlu: that.data.signinItg,
          brief: "会员签到送积分",
        },
        function(res){
        if(res != "undefined" && res.return_no == 1){
          //这里是诚诚之前写的：、
          // 设置今日签到标志、同时显示签到奖励
          that.setData({
            todaySignin:1,
            display_Signin_Reward:true
          })
          //这里调用onShow()：签到成功后，获得积分需要刷新一下【我的积分】
          that.onShow()
        }else{
          wx.showModal({
            title:res.return_msg,
            showCancel:false
          })
        }
        })
      }else{
        wx.showModal({
          title:res.return_msg,
          showCancel:false
        })
      }
    }
    )

  
  },


  // 切换上一个月
  lastMonth() {
    this.cur_date.setMonth(this.cur_date.getMonth() - 1);
    this.loadMonthCalendar();
  },
  // 切换下一个月
  nextMonth() {
    this.cur_date.setMonth(this.cur_date.getMonth() + 1);
    this.loadMonthCalendar();
  },

  // 加载签到记录
  loadMonthCalendar() {
    let days = this.getMonthDay();

    // 读取接口签到记录
    this.loadMonthSignin(days[0][0].yearmonthday,days[days.length-1][6].yearmonthday)
    .then(res => {
      if(res.includes(`${this.cur_date.getFullYear()*10000+(this.cur_date.getMonth()+1)*100+this.cur_date.getDate()}`)){
        this.setData({
          todaySignin:1,
        })
      }
      //呈现到页面上
      days.forEach(r => {
        r.forEach(d => {
          d.signin = res.includes(d.yearmonthday+"")
        });
      });
      this.setData({
        cur_display: `${this.cur_date.getFullYear()}年${this.cur_date.getMonth()+1}月`,
        days: days,
        loading: false
      });
    });
  },

  //加载某个月的签到记录
  loadMonthSignin(startDate,endDate) {
    return new Promise(solve => {
      // Api请求：05-001 会员签到信息查询
      getApp().loginPromise.then(v => {
        Request_get.get(
        config.domainName+"api_wxmkt_server/mbrsgn/listwxmbrsign",
        {
          bdate:startDate+"",
          edate:endDate+"",
        },res => {
          solve(res.return_data.filter(i => i.sgncnt).map(i=>i.sgndat));
        });
      })
    });
  },

  getMonthDay() {
    let date = new Date(this.cur_date.getTime());
    let cm = date.getMonth();
    let cy = date.getFullYear();
    date.setDate(1);
    let offsetDay = date.getDay() ? (2 - date.getDay()) : -5;
    date.setDate(offsetDay);
    let days = [];
    while (date.getFullYear() < cy ||
      (date.getFullYear() == cy && date.getMonth() <= cm)) {
      let row = [];
      for (let i = 0; i < 7; i++) {
        let yearmonth = date.getFullYear() * 100 + date.getMonth() + 1;
        let day = date.getDate();
        row.push({
          yearmonthday:yearmonth*100+day,
          ncm: cm != date.getMonth(),
          date: day
        });
        date.setDate(date.getDate() + 1);
      }
      days.push(row);
    }
    return days;
  },





  onShow: function () {
    var that = this
    getApp().loginPromise.then(v => {	//app.js的Promise成功回调（全局变量赋值成功后才执行请求）
      /** Api请求：04-001 会员信息查询（验证已绑定） **/
      Request_get.get(
        config.domainName+"api_wxmkt_server/mbrreg/findwxmbr",
        {},
        function(res){
          if(res != "undefined" && res.return_no == 1){
            that.setData({vlditg:res.return_data.vlditgvlu})
          }else{
            wx.showModal({
              title:res.return_msg
            });
          }
        }
      )
    })
	},
})